import { flushSync } from "react-dom";
import { useTheme } from "./ThemeProvider";

interface ModeToggleLiteProps {
    children: React.ReactNode;
    className?: string
}

export const ModeToggleLite = ({
    className,
    children,
    ...props
}: ModeToggleLiteProps) => {

    const { theme, setTheme } = useTheme();
    // 切换主题颜色
    const toggleDarkMode = (event: React.MouseEvent) => {
        console.log(theme)
        /**
         * window.matchMedia('(prefers-reduced-motion: reduce)').matches
         * 判断用户是否开启了动画减弱功能
         */
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        const isAppearanceTransition = document.startViewTransition && !window.matchMedia('(prefers-reduced-motion: reduce)').matches
        if (!isAppearanceTransition) {
            setTheme(theme === 'dark' ? 'light' : 'dark')
            return
        }

        // 传入点击事件，从点击处开始扩散。否则从右上角开始扩散
        const x = event.clientX
        const y = event.clientY
        const endRadius = Math.hypot(
            Math.max(x, innerWidth - x),
            Math.max(y, innerHeight - y),
        )
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        const transition = document.startViewTransition(() => {
            flushSync(() => {
                setTheme(theme === 'dark' ? 'light' : 'dark')
                console.log(theme)
            })
        })
        console.log(theme)
        transition.ready.then(() => {
            const clipPath = [
                `circle(0px at ${x}px ${y}px)`,
                `circle(${endRadius}px at ${x}px ${y}px)`,
            ]
            document.documentElement.animate(
                {
                    clipPath: theme === 'light' ? [...clipPath].reverse() : clipPath,
                },
                {
                    duration: 400,
                    easing: 'ease-out',
                    pseudoElement:
                        theme === 'light'
                            ? '::view-transition-old(root)'
                            : '::view-transition-new(root)',
                },
            )
        })
    }
    return (
        <div onClick={toggleDarkMode} className={className} {...props}>
            {children}
        </div>
    )
}